import React, {useState, useEffect, useMemo} from 'react';
import { get_umt, obj_empty, uJob, cline, BtTxt, obj_int, for_obj, is_empty, obj_str, loc, PanelFind, Ret, Title, filter_row, useCmd,
    useHigh, GridTable } from 'sui';
import { DlgTask } from '../../pair/task/ctl';
import { PsnView } from '../../pair/task/psn';
import { load_cage, load_stock, load_rule } from '../../pair/task/cmd';
import { reload, fix_psn } from './cmd';
import { User } from 'cache';

const TaskView = ({ cur, hreturn }) => {
    const [rule, setRule] = useState();
    const [row, setRow] = useState();
    const [main, setMain] = useState();
    const [stock_g, stockG] = useState();
    const [stock_t, stockT] = useState();
    const [cage, setCage] = useState();
    const [open_task, openTask] = useState(false);
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        load_rule(setRule);
        load_stock(stockG, stockT);
    }, []);

    useEffect(() => {
        reload(null, setMain, cur);
        load_cage(cur, setCage);
    }, [cur]);

    useEffect(() => {
        if (is_empty(main)) {
            setRow(null);
            return;
        }

        const batch = {};

        main.forEach(d => {
            if (!d.batch) {
                return;
            }

            const psn = obj_str(d, "sn");
            const ball = obj_str(d, "ball");
            const snum = obj_int(d, "num");

            d.batch.forEach(v => {
                const tmp = batch[v.sn];
                if (tmp) {
                    tmp.psn.add(psn);
                    return;
                }

                const set = new Set();
                set.add(psn);

                batch[v.sn] = {
                    dw: obj_str(v, "dw"),
                    std: obj_str(v, "std"),
                    sub: obj_str(v, "sub"),
                    ball: ball,
                    snum: snum,
                    psn: set,
                };
            })
        });

        const setVal = (data, tp) => {
            if (is_empty(data)) {
                return;
            }

            data.forEach(d => {
                const sn = obj_str(d, "sn");

                if (batch[sn]) {
                    batch[sn]["num"] = obj_int(d, "num");
                    batch[sn]["mt"] = tp;
                }
            });
        };

        setVal(stock_g, "G");
        setVal(stock_t, "T");

        const ret = [];

        for_obj(batch, (k, v) => {
            ret.push({
                sn: k,
                ...v
            });
        });

        ret.forEach((d, i) => {
            const pnum = d.psn.size;
            let dnum = Math.floor(d.num / d.snum);
            if (dnum > pnum) {
                dnum = pnum;
            }

            d["index"] = i + 1;
            d["pnum"] = d.psn.size;
            d["dnum"] = dnum;
        });

        setRow(ret);
    }, [main, stock_g, stock_t]);

    const getRow = useMemo(() => {
        const lst = ["sn"];
        return filter_row(row, lst, umd.filter);
    }, [row, umd.filter]);

    if (umd.isFin("psn")) {
        return <PsnView data={main} hreturn={umd.hreturn} cur={umd.cur} fix_col={fix_psn()}/>
    }

    const act = {
        "task": v => {
            if (obj_empty(rule)) {
                alert(loc("l_708"));
                return;
            }

            umd.startWait();

            const cmd = {
                usn: User.userName(),
                uname: User.uName(),
                sn: obj_str(umd.cur, "sn"),
                dw: obj_str(umd.cur, "dw"),
                mt: obj_str(umd.cur, "mt"),
                snum: obj_int(umd.cur, "snum"),
                tsn: obj_str(cur, "sn"),
                num: obj_int(v, "dnum"),
                cage: obj_str(v, "cage"),
            };

            uJob(null, "away/task",
                {
                    line: cline(),
                    v: cmd
                }, r => reload(umd.endWait, setMain, cur), e => umd.setErr(), true);
        }
    };

    const pact = {
        "task": (v) => openTask(true)
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70, frozen: true},
        {name: loc("l_238"), key: 'e_opt', width: 180, frozen: true, formatter: (props) => {
            const d = props.row;
            return (
                <div className="inline-flex">
                    <BtTxt hcmd={() => umd.pact(null, d, "psn")}>{loc("l_703")}</BtTxt>
                    <BtTxt hcmd={() => umd.pact(pact, d, "task")}>{loc("l_706")}</BtTxt>
                </div>
            );
        }},
        {name: loc("l_488"), key: 'sn', width: 100},
        {name: loc("l_714"), key: 'ball', width: 100},
        {name: loc("l_720"), key: 'mt', width: 70, formatter: props => {
            const d = props.row;
            const v = obj_str(d, "mt");
            return get_umt(v);
        }},
        {name: loc("l_802"), key: 'dw', width: 100},
        {name: loc("l_715"), key: 'std', width: 100},
        {name: loc("l_801"), key: 'sub', width: 100},
        {name: loc("l_716"), key: 'num', width: 100},
        {name: loc("l_717"), key: 'snum', width: 200},
        {name: loc("l_718"), key: 'pnum', width: 200},
        {name: loc("l_719"), key: 'dnum', width: 200},
    ];

    const Right = () => (
        <div className="inline-flex">
            <Ret className="ml-4" hcmd={hreturn}/>
        </div>
    );

    return (
        <div className="flex flex-col">
            <PanelFind left={<Title mod={obj_str(cur, "sn")} sub={loc("l_706")}/>} right={<Right/>} hcmd={umd.setFilter}/>
            <GridTable high={high} col={col} row={getRow}/>
            <DlgTask open={open_task} hcmd={v => umd.act(act, v)} setOpen={openTask} data={umd.cur} main={main} cage={cage}/>
        </div>
    );
};

export {TaskView};
